﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace KD.Sms.SerialServer
{
    public class PLY650_Com
    {
        /// <summary>
        /// 重量读取线程
        /// </summary>
        private Thread _thrdRead;
        /// <summary>
        /// 线程控制开关
        /// </summary>
        private bool _bRun = false;
        SerialClass _objCom;
        private int E_Interval { set; get; }
        public event EventHandler<CommonEventArgs> ReadEvent;
        bool _bReveice = true;
        public static string _strClassName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;

        public PLY650_Com(string com, int interval)
        {
            E_Interval = interval;
            _objCom = new SerialClass(com);
            _objCom.DataReceived += new SerialClass.SerialPortDataReceiveEventArgs(sc_DataReceived);
        }


        /// <summary>
        /// 
        /// </summary>
        public void DoRead()
        {
            _bRun = true;
            _thrdRead = new Thread(new ThreadStart(DoReadListening));
            _thrdRead.IsBackground = true;
            _thrdRead.Start();
        }

        /// <summary>
        /// 停止光幕数据读取
        /// </summary>
        public void DoStop()
        {
            _objCom.closePort();
            _bRun = false;
            System.Threading.Thread.Sleep(E_Interval);
            if (_thrdRead != null)
                _thrdRead.Abort();
        }

        /// <summary>
        /// 光幕数据读取
        /// </summary>
        private void DoReadListening()
        {
            Byte[] _bySendStart = new Byte[8];
            _bySendStart[0] = 0x01;
            _bySendStart[1] = 0x03;
            _bySendStart[2] = 0x10;
            _bySendStart[3] = 0x00;
            _bySendStart[4] = 0x00;
            _bySendStart[5] = 0x01;
            _bySendStart[6] = 0x80;
            _bySendStart[7] = 0xca;
            System.Threading.Thread.Sleep(1500);
            try
            {
                int _iStep = 0;
                while (_bRun)
                {
                    if (_bReveice)
                    {
                        _iStep = 0;
                        _bReveice = false;
                        _objCom.SendData(_bySendStart, 0, 8);
                    }
                    else
                    {
                        _iStep++;
                        if (_iStep >= 6)
                        {
                            _iStep = 0;
                            _bReveice = true;
                            FormHelper.ApplicationShow(UI.MsgType.Error, "超过5秒未收到仪表重量，系统自动重发指令!");
                        }
                    }
                    System.Threading.Thread.Sleep(E_Interval < 500 ? 500 : E_Interval);
                }
            }
            catch (Exception ex)
            {
                EventHelper.DispatchEventAsync<CommonEventArgs>(this, this.ReadEvent, new CommonEventArgs(ex.StackTrace));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="bits"></param>
        int _iWeight;
        string[] _arrWeight;
        string _strReadData;
        decimal _dWeight;
        public void sc_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e, byte[] _byReadValue)
        {
            _strReadData = "";
            for (int i = 0; i < _byReadValue.Length; i++)
            {
                _strReadData = _strReadData + _byReadValue[i].ToString("X").PadLeft(2, '0') + " ";
            }
            if (_strReadData.IndexOf("01 03 02", 0) >= 0)
            {
                _arrWeight = _strReadData.Split(' ');
                if (_arrWeight.Length > 6)
                {
                    _iWeight = GetHexadecimalValue(_arrWeight[3] + _arrWeight[4]);
                    if (_iWeight > 32767)
                        _iWeight = _iWeight - 65536;
                }

                _dWeight = decimal.Parse((_iWeight * 1.0 / 100).ToString("F2"));
                EventHelper.DispatchEventAsync<CommonEventArgs>(this, this.ReadEvent, new CommonEventArgs(_dWeight));
            }
            _bReveice = true;
        }

        /// <summary>
        /// 十六进制换算为十进制
        /// </summary>
        /// <param name="strColorValue"></param>
        /// <returns></returns>
        public static int GetHexadecimalValue(String strColorValue)
        {
            char[] nums = strColorValue.ToCharArray();
            int total = 0;
            try
            {
                for (int i = 0; i < nums.Length; i++)
                {
                    String strNum = nums[i].ToString().ToUpper();
                    switch (strNum)
                    {
                        case "A":
                            strNum = "10";
                            break;
                        case "B":
                            strNum = "11";
                            break;
                        case "C":
                            strNum = "12";
                            break;
                        case "D":
                            strNum = "13";
                            break;
                        case "E":
                            strNum = "14";
                            break;
                        case "F":
                            strNum = "15";
                            break;
                        default:
                            break;
                    }
                    double power = Math.Pow(16, Convert.ToDouble(nums.Length - i - 1));
                    total += Convert.ToInt32(strNum) * Convert.ToInt32(power);
                }

            }
            catch (System.Exception ex)
            {
                String strErorr = ex.ToString();
                return 0;
            }


            return total;
        }

    }
}
